<template>
  <div>
    <h1>Multiple Timers</h1>
    <div>
      <button type="button" @click="stoptimer1Scope">stoptimer1Scope</button>

      <button type="button" @click="stoptimer2Scope">stoptimer2Scope</button>

      <button type="button" @click="runtimer1Scope">runtimer1Scope</button>

      <button type="button" @click="runtimer2Scope">runtimer2Scope</button>

      <button type="button" @click="ganrao">干扰</button>
    </div>
    <div style="font-size: 30px" v-for="(item, index) in rac" :key="index">
      {{ item }}
    </div>

    <!-- <div style="font-size: 30px">
      {{ timer2.time }}
    </div> -->

    <!-- <button @click="createTimer">Add Timer</button> -->
    <!-- <div v-for="(timer, index) in timers" :key="index">
      <p>Timer {{ index + 1 }}: {{ timer.time }} seconds</p>
      <button @click="removeTimer(index)">Remove Timer</button>
    </div> -->
  </div>
</template>

<script setup>
import { ref, effectScope, getCurrentScope, onScopeDispose, reactive } from 'vue'

// 创建一个计时器的组合函数
function useTimer() {
  // 使用 effectScope 创建作用域
  const scope = effectScope()
  return scope
}

function srun(scope, step = 1000) {
  const time = ref(0)
  let interval

  scope.run(() => {
    // 开启计时器
    interval = setInterval(() => {
      console.log(time.value)

      time.value++
    }, step)

    // 在作用域销毁时清理定时器
    onScopeDispose(() => {
      clearInterval(interval)
      console.log('Timer stopped and resources cleaned up.')
    })
  })

  return { time }
}

let timer1 = useTimer()

console.log(timer1)

let rac = reactive([])

const runtimer1Scope = () => {
  let { time } = srun(timer1)
  rac.push(time)
}

const stoptimer1Scope = () => {
  timer1.stop()
}

let timer2 = useTimer()

const runtimer2Scope = () => {
  let { time } = srun(timer2)
  rac.push(time)
}

const stoptimer2Scope = () => {
  timer2.stop()
}

const ganrao = () => {
  rac[0].value = 20000
}

// 管理多个计时器
// const timers = ref([])

// 创建新计时器
// function createTimer() {
//   const newTimer = useTimer()
//   timers.value.push(newTimer)
// }

// 移除计时器并清理作用域
// function removeTimer(index) {
//   const timerToRemove = timers.value[index]
//   if (timerToRemove && timerToRemove.scope) {
//     timerToRemove.scope.stop() // 停止该作用域并触发清理
//   }
//   timers.value.splice(index, 1) // 从列表中移除计时器
// }
</script>
